package com.junci.mtest.utils;

import static android.content.Context.CLIPBOARD_SERVICE;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 默默
 * @time 2018/2/5  18:55
 * @E-mail yangmo@yingshe.com
 */

public class StringUtil {
    public static void copyString(Context context,String string){
        try {
            ClipboardManager myClipboard;
            myClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
            ClipData myClip;
            myClip = ClipData.newPlainText("text", string);//text是内容
            myClipboard.setPrimaryClip(myClip);
//            ToastUtil.show(context,"复制成功");
        }catch (Exception e){
        }
    }

    //保留两位小数
    public static String numFormat(float s){
        return String.format("%.2f", s);
    }

    //是否科学计数法
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    public static String hidePhone(String str){
        String str_2 = str.replaceAll("(?<=[\\w]{3})\\w(?=[\\w]{4})", "*");
        return str_2;
    }
    public static String hideIdcard(String str){
        String str_2 = str.replaceAll("(?<=[\\w]{6})\\w(?=[\\w]{4})", "*");
        return str_2;
    }
    public static String hideName(String str){
        String str_2 = str.replaceAll("(?<=[\\w]{1})\\w(?=[\\w]{0})", "*");
        return str_2;
    }
    /**
     * 校验用户密码：字母，数字，至少两种，6-16个字符
     */
    public static boolean validateUserPassword(String passport) {
        boolean res = true;
        if (passport.length()<6&&passport.length()>16) {
            LogUtil.s("--------6---");
            res =  true;
        }else{
            if(passport.matches("[0-9]+")||passport.matches("[a-z]+")) {
                LogUtil.s("--------num---");
                res =  true;
            }else{
                res =  false;
            }
            //check that there are letters
        }
        return res;
             //nope no letters, stop checking and fail!
        //check if there are any numbers

             //nope no numbers, stop checking and fail!

        //everything has passed so far, lets return valid


    }
    /**
     * 校验安全密码：字母，数字，至少两种，6-12个字符
     */
    public static boolean validateUserSafePassword(String passport) {


        if (passport.length()!=6) {
            LogUtil.s("--------6---");
            return true;
        }
        if(!passport.matches("[0-9]+")) {
            LogUtil.s("--------num---");
            return true;
        }

        return false;
        //check that there are letters
        //nope no letters, stop checking and fail!
        //check if there are any numbers

        //nope no numbers, stop checking and fail!

        //everything has passed so far, lets return valid


    }
    public static boolean isEmpty(String s){
        if(s==null){
         return true;
        }
        return s.isEmpty();
    }
    public static boolean isHave(String s){
        if(s==null){
            return false;
        }
        return !s.isEmpty();
    }


    public static String urlEnodeUTF8(String code) {
        String result = code;
        try {
            result = URLEncoder.encode(code, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    /**
     * 判断字段是否为身份证 符合返回ture
     * @param str
     * @return boolean
     */
    public static  boolean isIdCard(String str) {
        /**
         * 身份证正则表达式
         */
        String IDCARD="((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)[0-9]{4})" +
                "(([1|2][0-9]{3}[0|1][0-9][0-3][0-9][0-9]{3}" +
                "[Xx0-9])|([0-9]{2}[0|1][0-9][0-3][0-9][0-9]{3}))";
        if(TextUtils.isEmpty(str)) return false ;
        if(str.trim().length() == 15 || str.trim().length() == 18) {
            return Regular(str,IDCARD);
        }else {
            return false ;
        }
    }

    /**
     * 匹配是否符合正则表达式pattern 匹配返回true
     * @param str 匹配的字符串
     * @param pattern 匹配模式
     * @return boolean
     */
    private static  boolean Regular(String str,String pattern){
        if(null == str || str.trim().length()<=0)
            return false;
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    public static int validateUserPasswords(String passport) {
        passport = new String(passport.getBytes());
        Pattern pattern2 = Pattern.compile("[\u4e00-\u9fa5]+");
        Matcher match2 = pattern2.matcher(passport);
        if (match2.find() == true) {
            return 1;
        }


        Pattern pattern3 = Pattern.compile("[\\s\u4e00-\u9fa5]");
        Matcher match3 = pattern3.matcher(passport);
        if (match3.find() == true) {
            return 2;
        }


        Pattern pattern4 = Pattern.compile("\\*");
        Matcher match4 = pattern4.matcher(passport);
        if (match4.find()) {
            return 3;
        }


        return 0;
    }
    public static boolean checkEmail(String email){

        if (email !=null || email.length()>0){

 Pattern pattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

            Matcher matcher = pattern.matcher(email);

            return matcher.find();

        }

        return false;

    }
    public static boolean isLegalName(String name){
        if (name.contains("·") || name.contains("•")){
            if (name.matches("^[\\u4e00-\\u9fa5]+[·•][\\u4e00-\\u9fa5]+$")){
                return true;
            }else {
                return false;
            }
        }else {
            if (name.matches("^[\\u4e00-\\u9fa5]+$")){
                return true;
            }else {
                return false;
            }
        }
    }

    public static boolean checkBankCard(String cardId) {
        if (StringUtil.isEmpty(cardId)) {
            return false;
        }
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }
    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     *
     * @param nonCheckCodeCardId
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }


    public static boolean isMobileNO(String mobiles) {

        Pattern p = Pattern
                .compile("^(0|86|17951)?(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$");
        if (mobiles.isEmpty()) {
            return false;
        }
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    public static void copyClean(Context context){
        try {
            ClipboardManager myClipboard;
            myClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
            ClipData myClip;
            myClip = ClipData.newPlainText(null, "");//text是内容
            myClipboard.setPrimaryClip(myClip);
        }catch (Exception e){
        }
    }
    public static String formatTosepara(float data) {
        try {
            DecimalFormat df = new DecimalFormat("#,###.00");
            String  s = df.format(data);
            return s;
        }catch (Exception e){
            return data+"";
        }
    }


    /**
     * 格式化
     */
    private static DecimalFormat dfs = null;

    public static DecimalFormat format(String pattern) {
        if (dfs == null) {
            dfs = new DecimalFormat();
        }
        dfs.setRoundingMode(RoundingMode.FLOOR);
        dfs.applyPattern(pattern);
        return dfs;
    }
    /**
     * 转换数字以万为单位
     * @param num 要转化的数字
     * @param digit 保留的位数 可传null
     * @return
     */
    public static Object conversion(long num, Integer digit) {
        String unit = "";
        double newNum  = 0;
        if(num < 100000){
            return num;
        }
        else if(num>100000000){
            unit = "亿";
            newNum = num / 100000000.0;
            if(digit != null){
                String numStr = String.format("%." +digit +"f", newNum);
                return numStr + unit;
            }
        }
        else if(num>100000){
             unit = "万";
             newNum = num / 10000.0;
            if(digit != null){
                String numStr = String.format("%." +digit +"f", newNum);
                return numStr + unit;
            }
        }
        return newNum + unit;
    }

    public static String getMD5(String val){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(val.getBytes());
            byte[] m = md5.digest();//加密
            return getString(m);
        }catch (Exception e){
            return "";
        }
    }

    private static String getString(byte[] b){
        StringBuffer buf = new StringBuffer();
        for(int i = 0; i < b.length; i ++){
            int a = b[i];
            if(a<0)
                a+=256;
            if(a<16)
                buf.append("0");
            buf.append(Integer.toHexString(a));

        }
        return buf.toString();  //32位
//        return buf.toString().substring(8,24);   //16位
    }
    public static String base64Ecode(String str){

        String encodedString = "";
        try {
            encodedString = Base64.encodeToString(str.getBytes("UTF-8"), Base64.NO_WRAP);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedString;
    }
    public static String base64Dcode(String str){
        String decodedString =new String(Base64.decode(str,Base64.DEFAULT));
        return decodedString;
    }

    public static String urlEncode(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            throw new RuntimeException("URLEncoder.encode() failed for " + s);
        }
    }
    public static String replaceSpace(String myString){
       String newString = myString.replaceAll("(\r\n|\r|\n|\n\r)", "");
       return newString;
    }

    /**
     * 将超过8个字符的字符串，截取8个字符并加...在后面
     *
     * @param string 要截取的字符串
     * @return
     */
    public static String subShortNickName(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        } else {
            if (string.length() > 8) {
                string = string.substring(0, 6) + "...";
            }
        }
        return string;
    }

    public static String subShort(String string,int suble) {
        if (TextUtils.isEmpty(string)) {
            return "";
        } else {
            if (string.length() >suble) {
                string = string.substring(0,suble-1) + "...";
            }
        }
        return string;
    }


}

